﻿using CorpStore.Common;
using CorpStore.Models;
using CorpStore.ViewModels;
using Newtonsoft.Json;
using StoreHelper;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Threading.Tasks;
using Windows.ApplicationModel.Background;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.Storage;
using Windows.Storage.Search;
using Windows.Storage.Streams;
using Windows.UI.Core;
using Windows.UI.ViewManagement;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;

// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238

namespace CorpStore
{
    /// <summary>
    /// An empty page that can be used on its own or navigated to within a Frame.
    /// </summary>
    public sealed partial class GroupDetailsPage : BasePage
    {
        GroupDetailsViewModel viewModel = new GroupDetailsViewModel();
        CoreDispatcher dispatcher;

        public GroupDetailsPage()
        {
            InitializeComponent();
            DataContext = viewModel;

            // capture our core dispatcher so we can run code on our UI thread
            dispatcher = Window.Current.Dispatcher;
        }


        protected async override void LoadState(object navigationParameter, Dictionary<string, object> pageState)
        {
            await viewModel.InitOrRestoreStateAsync(navigationParameter as string, pageState);
        }


        protected override void SaveState(Dictionary<string, object> pageState)
        {
            viewModel.SaveState(ref pageState);
        }


        /// <summary>
        /// Invoked when an item within a group is clicked.
        /// </summary>
        /// <param name="sender">The GridView (or ListView when the application is snapped)
        /// displaying the item clicked.</param>
        /// <param name="e">Event data that describes the item clicked.</param>
        private void ItemView_ItemClick(object sender, ItemClickEventArgs e)
        {
            showDetailsPage(e.ClickedItem as PackageInfo);
        }


        private void showDetailsPage(PackageInfo app)
        {
            NavData navData = new NavData() { CurrentApp = app };
            string serializedData = JsonConvert.SerializeObject(navData);
            Frame.Navigate(typeof(AppDetailsPage), serializedData);
        }


        private void SearchBoxEventsSuggestionsRequested(SearchBox sender, SearchBoxSuggestionsRequestedEventArgs args)
        {
            var deferral = args.Request.GetDeferral();
            try
            {
                List<PackageInfo> foundApps = viewModel.GetAppsByName(args.QueryText);
                foreach (PackageInfo app in foundApps)
                {
                    Uri imageUri = new Uri(app.LogoFn);
                    args.Request.SearchSuggestionCollection.AppendResultSuggestion(
                        app.DisplayName,
                        app.Version ?? "",
                        app.FamilyName,
                        RandomAccessStreamReference.CreateFromUri(imageUri),
                        "No Image Available");
                }
            }
            finally
            {
                deferral.Complete();
            }
        }


        private void SearchBoxSuggestions_ResultSuggestionChosen(SearchBox sender, SearchBoxResultSuggestionChosenEventArgs args)
        {
            PackageInfo app = viewModel.CurrentGroup.Applications.Where(a => a.FamilyName.Equals(args.Tag)).FirstOrDefault();
            showDetailsPage(app);
        }

        private void logErr(string msg, params object[] p)
        {
            App.LogErr(msg, p);
        }

        private void logErrWithMsg(string msg, params object[] p)
        {
            App.LogErrWithMsg(msg, p);
        }

        private void logInfo(string msg, params object[] p)
        {
            App.LogInfo(msg, p);
        }

        private void logInfoWithMsg(string msg, params object[] p)
        {
            App.LogInfoWithMsg(msg, p);
        }


        private void logInfoWithToast(string msg, params object[] p)
        {
            App.LogInfoWithToast(msg, p);
        }


        private async void btnRefresh_Click(object sender, RoutedEventArgs e)
        {
            await viewModel.RefreshCurrentGroupAsync();
        }


        private async void BasePage_Loaded(object sender, RoutedEventArgs e)
        {
            await StoreHelper.GenLib.SleepAsync(3000);
        }

    }
}
